package com.atguigu.yygh.hosp.listener;

import com.atguigu.yygh.hosp.service.ScheduleService;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.mq.MqConst;
import com.atguigu.yygh.mq.RabbitService;
import com.atguigu.yygh.vo.msm.MsmVo;
import com.atguigu.yygh.vo.order.OrderMqVo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mgx
 * @version 1.0
 * @description: TODO
 * @date 2022/9/7 22:07
 */
@Component
public class OrderMqListener {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    // 确认下单 -> 更新剩余可预约数 - n ， 走此方法
    // 取消预约 -> 更新剩余可预约数 + 1， 走此方法 -> 通过是否传回剩余可预约数判断是否是取消预约
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = MqConst.QUEUE_ORDER, durable = "true"), // 创建队列
                    exchange = @Exchange(name = MqConst.EXCHANGE_DIRECT_ORDER, durable = "true"), // 创建交换机
                    key = {MqConst.ROUTING_ORDER} // 绑定关系
            )
    })
    public void consume(OrderMqVo orderMqVo, Message message, Channel channel) {
        // 获取到排班id和剩余可预约数
        Integer availableNumber = orderMqVo.getAvailableNumber();
        String scheduleId = orderMqVo.getScheduleId();
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(availableNumber != null) {
            // 确认下单
            // 更新
            boolean flag = scheduleService.updateAvailableNumber(scheduleId, availableNumber);
        }else {
            // 取消预约
            scheduleService.cancelSchedule(scheduleId);
        }

        if(msmVo != null) {
            // 再把消息发送给service_sms模块，提醒用户
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }

    }
}
